import { asyncRoutes, constantRoutes } from '@/router'
import { getAuth } from '@/utils/auth'
/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */

export function filterAsyncRoutesById(routes, ids) {
  const res = []
  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermissionId(ids, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutesById(tmp.children, ids)
      }
      res.push(tmp)
    }
  })
  return res
}
function hasPermissionId(ids, route) {
  if (route.meta && route.meta.id) {
    return ids.some(id => {
      return route.meta.id === id
    })
  } else {
    return true
  }
}
const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
    // console.log(routes, 'routes')
  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      let accessedRoutes
      if (getAuth() && JSON.parse(getAuth()).length) {
        accessedRoutes = filterAsyncRoutesById(
          asyncRoutes,
          JSON.parse(roles)
        )
        // console.log(asyncRoutes, 'asyncRoutes')
        // console.log(accessedRoutes, 'accessedRoutes')
        // console.log(getAuth());
      } else {
        accessedRoutes = asyncRoutes
      }
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
